//
//  ForgetVC.m
//  UHealth
//
//  Created by hanyou on 15/3/24.
//  Copyright (c) 2015年 gjtx. All rights reserved.
//

#import "ForgetVC.h"
#import "iToast.h"
#import "AFNetworking.h"

#define CODE_BTN_TAG 10
#define SURE_BTN_TAG 20

@interface ForgetVC ()

@property (nonatomic,strong) UITextField    *fieldUser;
@property (nonatomic,strong) UITextField    *fieldPassword;
@property (nonatomic,strong) UITextField    *fieldCode;

@property (nonatomic,strong) NSTimer        *countTimer;
@property (nonatomic)        NSInteger      count;

@end

@implementation ForgetVC
-(id)init{
    self = [super init];
    if (self) {
        self.view.backgroundColor = kBacColor;
    }
    
    return self;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NavView * nav = [[NavView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, kNavHeight) andTitleStr:kLocal(@"forget_pw") andVC:self];
    [self.view addSubview:nav];
    [self initView];
    // Do any additional setup after loading the view.
}

-(void)initView{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, kNavHeight, WIDTH, HEIGHT - kNavHeight)];
    
    UILabel *hit1 = [[UILabel alloc]initWithFrame:CGRectMake(20, 5 , WIDTH-40, 20)];
    hit1.text = kLocal(@"hit2");
    hit1.font = [UIFont systemFontOfSize:12];
    [view addSubview:hit1];
    
    NSArray *imgArr = @[@"user",@"password",@"code"];
    for (int i = 0; i < 3; i++) {
        
        UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(23, 33+i*30, 25, 25)];
        img.image = [UIImage imageNamed:imgArr[i]];
        [view addSubview:img];
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(20, 60+ i*30, WIDTH - 40, 0.5)];
        lineView.backgroundColor = [UIColor grayColor];
        [view addSubview:lineView];
    }
    
    _fieldUser = [[UITextField alloc]initWithFrame:CGRectMake(60, 33, WIDTH-80, 30)];
    _fieldUser.font = [UIFont systemFontOfSize:13.0];
    _fieldUser.clearButtonMode = UITextFieldViewModeWhileEditing;
    _fieldUser.placeholder = kLocal(@"phone");
    _fieldUser.keyboardType = UIKeyboardTypeNumberPad;
    
    
    [view addSubview:_fieldUser];
    
    _fieldPassword = [[UITextField alloc]initWithFrame:CGRectMake(60, 63, WIDTH-80, 30)];
    _fieldPassword.font = [UIFont systemFontOfSize:13.0];
    _fieldPassword.placeholder = kLocal(@"password");
    _fieldPassword.secureTextEntry = YES; //密码
    _fieldPassword.keyboardType = UIKeyboardTypeASCIICapable;
    _fieldPassword.clearButtonMode = UITextFieldViewModeWhileEditing;
    [view addSubview:_fieldPassword];
    
    _fieldCode = [[UITextField alloc]initWithFrame:CGRectMake(60, 93, 220 - 65, 30)];
    _fieldCode.font = [UIFont systemFontOfSize:13.0];
    _fieldCode.placeholder = kLocal(@"code");
    _fieldCode.clearButtonMode = UITextFieldViewModeWhileEditing;
    _fieldCode.keyboardType = UIKeyboardTypeASCIICapable;
    [view addSubview:_fieldCode];
    
    UIButton *codeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    codeBtn.frame = CGRectMake(220, 93, WIDTH- 220-20, 25);
    [codeBtn setTitle:kLocal(@"getcode") forState:UIControlStateNormal];
    [codeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [codeBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [codeBtn.layer setMasksToBounds:YES];
    [codeBtn.layer setCornerRadius:5.0];//设置矩形是个圆角半径
    codeBtn.backgroundColor = kBlueColor;
    codeBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    codeBtn.tag  = CODE_BTN_TAG;
    [view addSubview:codeBtn];
    
    UIButton *regBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    regBtn.frame = CGRectMake(40, 150, view.frame.size.width - 80, 40);
    [regBtn setTitle:kLocal(@"sure") forState:UIControlStateNormal];
    [regBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [regBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [regBtn.layer setMasksToBounds:YES];
    [regBtn.layer setCornerRadius:1.0];//设置矩形是个圆角半径
    regBtn.backgroundColor = kBlueColor;
    regBtn.tag  = SURE_BTN_TAG;
    [view addSubview:regBtn];

    
    [self.view addSubview:view];
    

}

-(void)BtnCount:(NSTimer *)timer
{
    _count --;
    UIButton *btn = (UIButton *)timer.userInfo;
    if (_count <= 0) {
        btn.enabled = YES;
        [_countTimer invalidate];
        _countTimer = nil;
        [btn setTitle:kLocal(@"getcode") forState:UIControlStateNormal];
    }else{
        [btn setTitle:[NSString stringWithFormat:@"%d%@",(int)_count,kLocal(@"sec")] forState:UIControlStateNormal];
    }
    
}

- (void)BtnClick:(UIButton *)btn{
    NSString *user = _fieldUser.text;
    NSString *password = _fieldPassword.text;
    NSString *code = _fieldCode.text;
    
    if ((!user.length || (password.length<6 && password.length >12)|| !code.length) && btn.tag == SURE_BTN_TAG) {
        [[iToast makeText:kLocal(@"please_input_info")] show];
        return;
    }else if(btn.tag  == CODE_BTN_TAG){
        if (!user.length) {
            [[iToast makeText:kLocal(@"please_input_phone")] show];
            return;
        }
        btn.enabled = NO;
        _count = 60;
        [btn setTitle:[NSString stringWithFormat:@"%d%@",(int)_count,kLocal(@"sec")] forState:UIControlStateNormal];
        _countTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(BtnCount:) userInfo:btn repeats:YES];
        
    }
    [self.view endEditing:YES];
    
    if (!kNetIsOK) {
        [[iToast makeText:kLocal(@"netNoOk")] show];
        return;
    }
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer.timeoutInterval = 10;
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject: @"text/html"];
    NSString *postStr = [NSString stringWithFormat:@"%@/action/json/login.jsp",kBaseUrl];
    NSString *app_Version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];// app版本
    NSDictionary *parameters;
    
    
    if (btn.tag == CODE_BTN_TAG) {//获取验证码
        parameters = @{@"action": @"getverify",
                       @"mobile":user,
                       @"opt":@"2"};
    }else{//校验验证码
        parameters = @{@"action": @"getpwd",
                       @"mobile":user,
                       @"verify":code,
                       @"fromtype":@"1",
                       @"mobile_type":@"1",
                       @"app_line":app_Version};
        
    }
    

    

    
    [manager POST:postStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject){
        BOOL type = [[responseObject objectForKey:@"type"] boolValue];
        long  userid = [[responseObject objectForKey:@"userid"] integerValue];
        NSLog(@"%ld",userid);
        if (type) {
            if (btn.tag == CODE_BTN_TAG) {
                
            }else{//858780 永久验证码
                NSDictionary *parameters;
                parameters = @{@"action": @"memberSetForgetPwd",
                               @"userid":[NSString stringWithFormat:@"%ld",userid],
                               @"password":password,
                               @"fromtype":@"1",
                               @"mobile_type":@"1",
                               @"app_line":app_Version};
                [manager POST:postStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id response){
                    BOOL type = [[response objectForKey:@"type"] boolValue];
                    if (type) {
                        //主账号 插入或者更新
                        [[DBManage sharedManager]insertData:_user andTable:kUserTable];
                        
                        //家庭成员
                        [self dismissViewControllerAnimated:YES completion:nil];
                    }
                    
                    [[iToast makeText:[response objectForKey:@"msg"]] show];

                
                } failure:^(AFHTTPRequestOperation *operation, NSError *error){
                    kDebug(@"Error: %@", error);
                    [[iToast makeText:kLocal(@"netError")] show];
                    
                }];

                
            }
            
        }else{

        }
        [[iToast makeText:[responseObject objectForKey:@"msg"]] show];

    
    } failure:^(AFHTTPRequestOperation *operation, NSError *error){
        kDebug(@"Error: %@", error);
        [[iToast makeText:kLocal(@"netError")] show];
    }];
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
